package com.spring.utils;


import javax.sql.DataSource;
import java.sql.Connection;

/**
 * 链接的工具类，它用于从数据源中获取一个链接,并且实现和线程的绑定
 */
public class ConnectionUtils {

    private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 获取当前线程上的链接
     */
    public Connection getThreadConnection(){
        //1、先从ThreadLocal上进行获取
        Connection connection = tl.get();
        //2、判断当前线程上是否有链接
        try{
            if(connection == null){
                //3、从数据源中获取一个链接,并存入ThreadLocal中
                connection = dataSource.getConnection();
                tl.set(connection);
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return  connection;
    }


    public void removeConnection(){
        tl.remove();
    }

}
